<?php 

namespace App\Repositories;

use Config;

class SettingRepository extends Repository 
{
    public function model() 
    {
        return 'App\Models\Setting';
    }

    // 得到所有配置
    public function getAll()
    {
        static $setting;

        if ($setting && !isEmpty($setting)) { 
            return $setting;
        }

        $data = $this->model->all();
        $result = array();

        if (!$data->isEmpty()) {
            foreach ($data as $value) {
                $result[$value->item] = $value->value;
            }
        }

        $setting = collect($result);

        return $setting;
    }

    // 获取系统项
    public function get($item, $defaultValue = '')
    {
        $this->getAll()->get($item, $defaultValue);
    }

    // 保存单个系统项
    public function set($item, $value)
    {
        $object = $this->findBy('item', $item);

        if ($object) {
            return $object->update(['value'=>$value]);
        }

        return $this->create(['item'=>$item, 'value'=>$value]);
    }

    // 保存多个系统项
    public function sets(array $data)
    {
        unset($data['_token']);

        if (!empty($data)) {
            foreach ($data as $item => $value) {
                $this->set($item, $value);
            }
        }

        return true;
    }
}